﻿using BL_Client.ServiceReference1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UI
{
    public partial class Cities : System.Web.UI.Page
    {
        static BL_Client.IBL bl = new BL_Client.BL();
        static User user;

        public Cities()
        {
            user = bl.GetUserByEmail(User.Identity.Name);
        }

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (userIsAdmin(user)) //check the role of the user
                this.Page.MasterPageFile = "~/Admin.Master";
            else
                this.Page.MasterPageFile = "~/AvBait.Master";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (userIsAdmin(user))
                jTableScript.InnerHtml = @"<script  type=""text/javascript"">
                                            $(document).ready(function () {
                                                $('#CitiesTableContainer').jtable({
                                                    title: 'Table of Cities',
                                                    paging: true,
                                                    pageSize: 10,
                                                    sorting: true,
                                                    defaultSorting: 'Name ASC',
                                                    actions: {
                                                        listAction: '/Cities.aspx/CitiesList',
                                                        createAction: '/Cities.aspx/CreateCity',
                                                        updateAction: '/Cities.aspx/UpdateCity',
                                                        deleteAction: '/Cities.aspx/DeleteCity'
                                                    },
                                                    fields: {
                                                        ID: {
                                                            key: true,
                                                            create: false,
                                                            edit: false,
                                                            list: false
                                                        },
                                                        Name: {
                                                            title: 'City Name',
                                                            width: '40%'
                                                        }
                                                    },
                                                    formCreated: function (event, data) {
                                                                    data.form.find('input[name=""Name""]').addClass('validate[required]');
                                                                    data.form.validationEngine();
                                                    },
                                                    formSubmitting: function (event, data) {
                                                        return data.form.validationEngine('validate');
                                                    },
                                                    formClosed: function (event, data) {
                                                        data.form.validationEngine('hide');
                                                        data.form.validationEngine('detach');
                                                    }
                                                });

                                                $('#CitiesTableContainer').jtable('load');
                                            });
                                        </script>";
            else if (user.Role == Role.AvBait)
            {
                jTableScript.InnerHtml = @"<script  type=""text/javascript"">
                                            $(document).ready(function () {
                                                $('#CitiesTableContainer').jtable({
                                                    title: 'Table of Cities',
                                                    paging: true,
                                                    pageSize: 10,
                                                    sorting: true,
                                                    defaultSorting: 'Name ASC',
                                                    actions: {
                                                        listAction: '/Cities.aspx/CitiesList'
                                                    },
                                                    fields: {
                                                        ID: {
                                                            key: true,
                                                            create: false,
                                                            edit: false,
                                                            list: false
                                                        },
                                                        Name: {
                                                            title: 'City Name',
                                                            width: '40%'
                                                        }
                                                    },
                                                    formCreated: function (event, data) {
                                                                    data.form.find('input[name=""Name""]').addClass('validate[required]');
                                                                    data.form.validationEngine();
                                                    },
                                                    formSubmitting: function (event, data) {
                                                        return data.form.validationEngine('validate');
                                                    },
                                                    formClosed: function (event, data) {
                                                        data.form.validationEngine('hide');
                                                        data.form.validationEngine('detach');
                                                    }
                                                });

                                                $('#CitiesTableContainer').jtable('load');
                                            });
                                        </script>";
            }
        }

        [WebMethod(EnableSession = true)]
        public static object CitiesList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                //Get data from database
                int citiesCount = bl.GetAllCities().Count();
                List<City> cities = bl.GetCities(jtStartIndex, jtPageSize, jtSorting).ToList();

                //Return result to jTable
                return new { Result = "OK", Records = cities, TotalRecordCount = citiesCount };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object CreateCity(City record)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR"};

            try
            {
                if (bl.AddCity(record))
                {
                    City addedCity = record;
                    return new { Result = "OK", Record = addedCity };
                }
                else
                {
                    return new { Result = "ERROR", Message = "City insertion error" };
                }
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object UpdateCity(City record)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                bl.UpdateCity(record);
                return new { Result = "OK" };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object DeleteCity(int ID)
        {
            if (!userIsAdmin(user))
                return new { Result = "ERROR" };

            try
            {
                bl.RemoveCity(ID);
                return new { Result = "OK" };
            }
            catch (Exception ex)
            {
                return new { Result = "ERROR", Message = ex.Message };
            }
        }

        private static bool userIsAdmin(User user)
        {
            return (user.Role == Role.Admin);
        }
    }
}